﻿using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

/// <summary>
///   move smoothly in client side
///   in Server side: set the position directly
///   in Client side: set the next aim, and calculate the delta time
/// </summary>
// [NetworkSettings(sendInterval = 0.05f)] // the default interval is 0.1f
public class NetworkPosition : NetworkBehaviour {

    [SyncVar(hook = "onChangePosition")]
    private Vector2 _position;

    private float _lastTime;

    // ** use moveTowards
    private float _moveMaxSpeed;
    private Vector3 _moveAimPosition;

    // Update is called once per frame
    void Update() {
        if (isServer) {
            this.transform.position = _position;
        }
        else if (isClient) {
            this.transform.position =
                Vector3.MoveTowards(this.transform.position, _moveAimPosition, _moveMaxSpeed * Time.deltaTime);
        }
    }

    /// <summary>
    ///     this only works on server side
    /// </summary>
    /// <param name="p">the position</param>
    [Server]
    public void setPosition(Vector2 p) {
        _position = p;
    }

    void onChangePosition(Vector2 p) {
        var nextPosition = (Vector3) p;
        var changeDeltaTime = Time.time - _lastTime;
        var deltaPositionLength = (nextPosition - _moveAimPosition).magnitude;
        // Debug.Log("deltaT:" + changeDeltaTime);
        // Debug.Log("deltaP:" + deltaPositionLength);
        startMoveTowards(deltaPositionLength/changeDeltaTime, nextPosition);
        _lastTime = Time.time;
    }

    void startMoveTowards(float maxSpeed, Vector3 aimPosition) {
        // set a moveTowards task
        _moveMaxSpeed = maxSpeed;
        _moveAimPosition = aimPosition;
    }
}